package com.gitee.dupe.file.strategy.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.gitee.dupe.file.entity.Attachment;
import com.gitee.dupe.file.strategy.FileStrategy;
import com.gitee.dupe.file.utils.FileDataTypeUtil;
import org.springframework.web.multipart.MultipartFile;


/**
 * 文件策略接口
 *
 * @author LYH
 */
public abstract class AbstractFileStrategy implements FileStrategy {


    /**
     * 上传文件
     *
     * @param multipartFile 文件
     * @return 附件
     */
    @Override
    public Attachment upload(MultipartFile multipartFile) {
        String originalFilename = multipartFile.getOriginalFilename();
        if(originalFilename.contains("\\")) {
            originalFilename = CollUtil.getLast(StrUtil.split(originalFilename,'\\'));
        }

        Attachment attachment = new Attachment()
                .setSubmittedFileName(originalFilename)
                .setContextType(multipartFile.getContentType())
                .setDataType(FileDataTypeUtil.getDataType(multipartFile.getContentType()))
                .setSize(multipartFile.getSize())
                .setExt(FileUtil.extName(multipartFile.getOriginalFilename()));
        uploadFile(attachment, multipartFile);
        return attachment;
    }

    /**
     * 具体类型执行上传操作
     *
     * @param attachment    附件
     * @param multipartFile 文件
     * @throws Exception 异常
     */
    protected abstract void uploadFile(Attachment attachment, MultipartFile multipartFile);
}
